import { reactive } from './reactive.js'

export function ref(data) {
  const wrapper = {
    value: data
  }
  Object.defineProperty(wrapper, '__v_isRef', {
    value: true
  })
  return reactive(wrapper)
}

export function proxyRefs(obj) {
  return new Proxy(obj, {
    get(target, key, receiver) {
      const res = Reflect.get(target, key, receiver)
      return res.__v_isRef ? res.value : res
    },
    set(target, key, newValue, receiver) {
      const value = target[key]
      if(value['__v_isRef']) {
        value.value = newValue
        return true
      }
      return Reflect.set(target, key, newValue, receiver)
    }
  })
}

export function toRef(obj, key) {
  const wrapper = {
    get value() {
      return obj[key]
    },
    set value(val) {
      return obj[key] = val
    }
  }
  Object.defineProperty(wrapper, '__v_isRef', {
    value: true
  })
  return wrapper
}

export function toRefs(obj) {
  const o = {}
  for(const key in obj) {
    o[key] = toRef(obj, key)
  }
  return o
}